//
//  NetworkManager.swift
//  CopyWB
//
//  Created by imac on 2017/5/26.
//  Copyright © 2017年 iimac. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod {
    case GET
    case POST
}

class NetworkManager: AFHTTPSessionManager {
    
    // 静态区/常量/闭包
    // 在第一次访问时执行闭包，并且将结果保存到shared常量中
    static let shared = NetworkManager()
    
    // 利用一个函数隔离 get/post 请求
    ///
    /// - Parameters:
    ///   - method: GET / POST 请求
    ///   - urlString: URLString
    ///   - parameters:  请求的参数字典
    ///   - completion: 完成闭包[JSON (字典 / 数组) , 是否成功]
    func request(_ method : HTTPMethod = .GET,urlString : String , parameters : [String : String] , completion : @escaping (_ json : Any? , _ isSuccessed : Bool)->() ){
        
        // 成功的回调
        let success = {(task : URLSessionDataTask ,json : Any?)->() in
        
            completion(json, true)
        }
        // 失败的回调
        let failure = {(task : URLSessionDataTask? , error : Error )->() in
            
            completion(nil, false)
        }
        
        if method == .GET{
            
            get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        
        }else{
        
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
    
}
